package cn.ydxiaoshuai.common.util.api;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.ydxiaoshuai.common.api.vo.api.GarbageResponseBean;
import cn.ydxiaoshuai.common.constant.JDAIConts;
import com.alibaba.fastjson.JSON;

import java.util.Comparator;
import java.util.List;

/**
 * @author 小帅丶
 * @className GarbageUtil
 * @Description 垃圾分类查询工具类
 * @Date 2020/4/26-16:39
 **/
public class GarbageUtil {
    /**
     * @Author 小帅丶
     * @Description 垃圾分类查询工具类
     * @Date  2020/4/26 16:45
     * @param cityId 城市ID
     *               支持城市：310000(上海市)、330200(宁波市)、610100(西安市)、440300(深圳市)、北京市(110000)
     * @param imgBase64 图片的BASE64
     * @return java.lang.String
     **/
    public static String getGarbage(String cityId,String imgBase64){
        //请求的时间戳，精确到毫秒，timestamp有效期5分钟
        String timestamp = String.valueOf(System.currentTimeMillis());
        //签名，根据规则MD5(sectetkey+timestamp)
        String sign = SecureUtil.md5(JDAIConts.SECRETKEY+timestamp);
        //URL参数
        String url_params = JDAIConts.GARBAGEIMAGESEARCH_URL+"?appkey="+ JDAIConts.APPKEY+"&timestamp="+timestamp+"&sign="+sign;
        //BODY参数
        String body_params = "{\"imgBase64\":\""+imgBase64+"\",\"cityId\":\""+cityId+"\"}";
        //返回的结果
        String result = HttpUtil.post(url_params, body_params);
        return result;
    }
    /**
     * @Author 小帅丶
     * @Description 垃圾分类查询工具类
     * @Date  2020/4/26 16:45
     * @param cityId 城市ID
     *               支持城市：310000(上海市)、330200(宁波市)、610100(西安市)、440300(深圳市)、北京市(110000)
     * @param imgBase64 图片的BASE64
     * @return GarbageResponseBean
     **/
    public static GarbageResponseBean getGarbageBean(String cityId, String imgBase64){
        String result = getGarbage(cityId, imgBase64);
        GarbageResponseBean garbageResponseBean = JSON.parseObject(result, GarbageResponseBean.class);
        if(garbageResponseBean.getResult().getStatus()==0){
            List<GarbageResponseBean.ResultBean.GarbageInfoBean> garbage_info = garbageResponseBean.getResult().getGarbage_info();
            garbage_info.sort(Comparator.comparing(GarbageResponseBean.ResultBean.GarbageInfoBean::getConfidence).reversed());
            return garbageResponseBean;
        }else{
            return garbageResponseBean;
        }
    }
}
